import {
  put, takeLatest, takeEvery, all, call, select, fork,
} from 'redux-saga/effects'
import { push } from 'connected-react-router'
import { projectLabelView as projectDuck, canvas as canvasDuck, global as globalDuck } from 'ducks'
import getImageItemsPageInfo from 'graphql/getImageItemsPageInfo.graphql'
import deleteAll from 'graphql/deleteAll.graphql'
import deleteOne from 'graphql/deleteLabel.graphql'
import getItemInfo from 'graphql/getItemInfo.graphql'
import nextItem from 'graphql/nextItem.graphql'
import preItem from 'graphql/preItem.graphql'
import nextFinishItem from 'graphql/nextFinishItem.graphql'
import preFinishItem from 'graphql/preFinishItem.graphql'
import firstOrLast from 'graphql/itemFirstAndLast.graphql'
import { gqlQuery, gqlMutation } from './utils'

const tasks = {}

function* getImageItemPageInfoSaga(action) {
  const result = yield call(gqlQuery, getImageItemsPageInfo, { id: action.itemId })
  yield put(projectDuck.creators.actionReciveItemPage(result.itemsPage))
  if (result.itemsPage.length > 0) {
    yield put(projectDuck.creators.actionGetItemInfo(result.itemsPage[0].itemId))
  }
}

function* getImageItemInfoSaga(action) {
  const result = yield call(gqlQuery, getItemInfo, { id: action.itemId })
  yield put(projectDuck.creators.actionReciveItemInfo(result.itemInfo))
  yield put(canvasDuck.creators.actionInitItemImage())
}

function* initImage(action) {
  yield put(canvasDuck.creators.actionInitItemImage())
}

function* deleteAllSaga() {
  const itemId = yield select(projectDuck.selectors.activeItemId)
  yield call(gqlMutation, deleteAll, { itemId })
  yield put(projectDuck.creators.actionDeleteAll())
  yield put(projectDuck.creators.actionCloseDeleteModal())
}

function* deleteLabelSaga(action) {
  yield call(gqlMutation, deleteOne, { id: action.id })
  yield put(projectDuck.creators.actionDelete(action.id, action.index))
}

function* itemNav(action) {
  console.log(action.url, action.navType, tasks.task)
  const cTime = yield select(projectDuck.selectors.activeItemCreateTime)
  const fTime = yield select(projectDuck.selectors.activeItemFinishTime)
  const user = yield select(globalDuck.selectors.user)
  const projectId = yield select(projectDuck.selectors.projectId)
  const getState = action.state === 'all' ? ['label', 'done'] : [action.state]
  let queryFunc
  const queryParams = {
    pid: projectId,
    uid: user.id,
    state: getState,
  }
  if (action.state === 'done') {
    if (action.navType === 'pre') {
      queryFunc = preFinishItem
      queryParams.finishTime = fTime
    } else if (action.navType === 'next') {
      queryFunc = nextFinishItem
      queryParams.finishTime = fTime
    } else if (action.navType === 'first') {
      queryFunc = firstOrLast
      queryParams.order = { finish_time: 'desc' }
    } else if (action.navType === 'last') {
      queryFunc = firstOrLast
      queryParams.order = { finish_time: 'asc' }
    }
  } else if (action.navType === 'pre') {
    queryFunc = preItem
    queryParams.createTime = cTime
  } else if (action.navType === 'next') {
    queryFunc = nextItem
    queryParams.createTime = cTime
  } else if (action.navType === 'first') {
    queryFunc = firstOrLast
    queryParams.order = { create_at: 'asc' }
  } else if (action.navType === 'last') {
    queryFunc = firstOrLast
    queryParams.order = { create_at: 'desc' }
  }
  const result = yield call(gqlQuery, queryFunc, queryParams)
  if (result.project_task_item.length === 1) {
    console.log(result.project_task_item[0].id)
    yield put(push(`${action.url}/${result.project_task_item[0].id}`))
    yield put(projectDuck.creators.actionSetActiveItemId(result.project_task_item[0].id))
  }
}

function* itemNavDispatch(action) {
  const fieldTask = tasks.task
  if (fieldTask === undefined || !fieldTask.isRunning()) {
    const lastTask = yield fork(itemNav, action)
    tasks.task = lastTask
  } else {
    console.log('cancle')
  }
}

export default function* sagas() {
  yield all([
    takeLatest(projectDuck.types.INIT_ITEM_PAGE, getImageItemPageInfoSaga),
    takeLatest(projectDuck.types.GET_ITEM, getImageItemInfoSaga),
    takeLatest(projectDuck.types.RECIVE_ITEM, initImage),
    takeEvery(projectDuck.types.DELETE_ALL_SERVER, deleteAllSaga),
    takeEvery(projectDuck.types.DELETE_LABEL_SERVER, deleteLabelSaga),
    takeEvery(projectDuck.types.ITEM_NAV, itemNavDispatch),
  ])
}
